# -*- coding: utf-8 -*-
import os
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import *
from PyQt5.QtWebChannel import *
from PyQt5.QtGui import *

# # 控制台
# DEBUG_PORT = '5589'
# DEBUG_URL = 'http://127.0.0.1:%s' % DEBUG_PORT
# os.environ['QTWEBENGINE_REMOTE_DEBUGGING'] = DEBUG_PORT
# 网页链接
url = "/dist/index.html"

def fileDialog():
    # 打开文件选择对话框
    options = QFileDialog.Options()
    file_path, _ = QFileDialog.getOpenFileName(None, "选择文件", "", "所有文件 (*);;可执行程序 (*.exe);;压缩文件 (*.zip);;压缩文件 (*.7z)", options=options)
    
    if file_path:
        return file_path
    return None
        
def folderDialog():
    # 打开文件夹选择对话框
    options = QFileDialog.Options()
    folder_path = QFileDialog.getExistingDirectory(None, "选择文件夹", "", options=options)
    
    if folder_path:
        return folder_path
    return None

# 暴露函数
class WindowController(QObject):
    addResult = pyqtSignal(int)
    filspath = pyqtSignal(str)

    def __init__(self, window):
        super().__init__()
        self.window = window

    @pyqtSlot(int)
    def add(self,x):
        """测试"""
        result = 2
        self.addResult.emit(result)
        print(x)

    @pyqtSlot()
    def getfilepath(self):
        """获取文件路径"""
        path = fileDialog()
        if path:
            self.filspath.emit(path)
        else:
            self.filspath.emit("Null")

    @pyqtSlot(int, int)
    def moveWindow(self, x, y):
        """拖动窗口"""
        if self.window.isFullScreen():
            return
        else:
            self.window.move(x, y)

    @pyqtSlot(int, int, int, int)
    def resizeWindow(self, left, top, width, height):
        """调整窗口大小，并确保最小尺寸"""
        if self.window.isFullScreen():
            return
        else:
            if width < self.window.minimumWidth():
                width = self.window.minimumWidth()
            if height < self.window.minimumHeight():
                height = self.window.minimumHeight()
            self.window.setGeometry(left, top, width, height)

    @pyqtSlot()
    def minimizeWindow(self):
        """最小化窗口"""
        self.window.showMinimized()

    @pyqtSlot()
    def toggleWindow(self):
        """最大化和恢复窗口"""
        if self.window.isFullScreen():
            self.window.showNormal()
            return False
        else:
            self.window.showFullScreen()
            return True

    @pyqtSlot()
    def closeWindow(self):
        """关闭窗口"""
        self.window.close()

# 窗口相关
class ResizableWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowFlags(self.windowFlags() | Qt.FramelessWindowHint)  # 无边框窗口

        # 创建 WebView
        self.webview = QWebEngineView()
        self.setCentralWidget(self.webview)

        # 设置最小尺寸
        self.setMinimumSize(800, 600)  # 宽度和高度分别为800px和600px

        # 设置 QWebChannel
        self.channel = QWebChannel()
        self.controller = WindowController(self)
        self.channel.registerObject('windowController', self.controller)
        self.webview.page().setWebChannel(self.channel)

        # 加载 HTML
        self.webview.setUrl(QUrl.fromLocalFile(url))

        # 初始化拖动和调整大小变量
        self.is_dragging = False
        self.is_resizing = False
        self.resize_direction = None
        self.start_x = 0
        self.start_y = 0

        self.setMouseTracking(True)  # 启用鼠标跟踪

        # 创建调整大小手柄
        self.create_resize_handles()   
        
        
    def create_resize_handles(self):
        """创建调整手柄"""
        self.resize_handle_bottom_right = QWidget(self)
        self.resize_handle_bottom_right.setStyleSheet("background: transparent;")
        self.resize_handle_bottom_right.setFixedSize(16, 16)
        self.resize_handle_right = QWidget(self)
        self.resize_handle_right.setStyleSheet("background: transparent;")
        self.resize_handle_right.setFixedSize(16, self.height()-16)
        self.resize_handle_bottom = QWidget(self)
        self.resize_handle_bottom.setStyleSheet("background: transparent;")
        self.resize_handle_bottom.setFixedSize(self.width()-16, 16)

        self.update_resize_handles()

        # 设置手柄的光标样式
        self.resize_handle_bottom_right.setCursor(QCursor(Qt.SizeFDiagCursor))
        self.resize_handle_right.setCursor(QCursor(Qt.SizeHorCursor))
        self.resize_handle_bottom.setCursor(QCursor(Qt.SizeVerCursor))

    def update_resize_handles(self):
        """更新手柄位置"""
        self.resize_handle_bottom_right.setGeometry(self.width() - 16, self.height() - 16, 16, 16)
        self.resize_handle_right.setGeometry(self.width() - 16, 0, 16, self.height())
        self.resize_handle_bottom.setGeometry(0, self.height() - 16, self.width(), 16)
        """更新手柄尺寸"""
        self.resize_handle_right.setFixedHeight(self.height() - 16)
        self.resize_handle_bottom.setFixedWidth(self.width() - 16)

    def mousePressEvent(self, event: QMouseEvent):
        if event.button() == Qt.LeftButton:
            if self.is_on_resize_handle(event.pos()):
                self.is_resizing = True
                self.resize_direction = self.get_resize_direction(event.pos())
                self.start_x = event.globalX()
                self.start_y = event.globalY()
            else:
                self.is_dragging = True
                self.start_x = event.globalX()
                self.start_y = event.globalY()

    def mouseMoveEvent(self, event: QMouseEvent):
        if self.is_resizing:
            dx = event.globalX() - self.start_x
            dy = event.globalY() - self.start_y
            if self.resize_direction == 'bottom_right':
                self.resizeWindow(self.x(), self.y(), self.width() + dx, self.height() + dy)
            elif self.resize_direction == 'right':
                self.resizeWindow(self.x(), self.y(), self.width() + dx, self.height())
            elif self.resize_direction == 'bottom':
                self.resizeWindow(self.x(), self.y(), self.width(), self.height() + dy)
            self.start_x = event.globalX()
            self.start_y = event.globalY()
        elif self.is_dragging:
            dx = event.globalX() - self.start_x
            dy = event.globalY() - self.start_y
            self.move(self.x() + dx, self.y() + dy)
            self.start_x = event.globalX()
            self.start_y = event.globalY()

    def mouseReleaseEvent(self, event: QMouseEvent):
        self.is_dragging = False
        self.is_resizing = False

    def is_on_resize_handle(self, pos):
        return (self.resize_handle_bottom_right.geometry().contains(pos) or
                self.resize_handle_right.geometry().contains(pos) or
                self.resize_handle_bottom.geometry().contains(pos))

    def get_resize_direction(self, pos):
        if self.resize_handle_bottom_right.geometry().contains(pos):
            return 'bottom_right'
        elif self.resize_handle_right.geometry().contains(pos):
            return 'right'
        elif self.resize_handle_bottom.geometry().contains(pos):
            return 'bottom'
        return None

    def resizeWindow(self, left, top, width, height):
        """调整窗口大小，并确保最小尺寸"""
        if width < self.minimumWidth():
            width = self.minimumWidth()
        if height < self.minimumHeight():
            height = self.minimumHeight()
        self.setGeometry(left, top, width, height)
        self.update_resize_handles()  # 更新手柄位置

    def changeEvent(self, event):
        if event.type() == QEvent.WindowStateChange:
            if self.windowState() & Qt.WindowMaximized:
                self.controller.maximizeWindow()
            elif self.windowState() & Qt.WindowNoState:
                self.controller.restoreWindow()
        super().changeEvent(event)

if __name__ == '__main__':
    app = QApplication([])
    window = ResizableWindow()
    window.show()
    app.exec_()
